package com.gitee.li709.jmeter;

import cn.hutool.core.thread.ThreadUtil;
import com.gitee.li709.jmeter.client.NettyClient;
import org.apache.jmeter.samplers.SampleResult;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.CountDownLatch;

public class SampleResultManager {

    private SampleResult sampleResult;
    private CountDownLatch countDownLatch;

    private NettyClient nettyClient;

    public SampleResultManager(NettyClient nettyClient) {
        this.nettyClient = nettyClient;
    }

    public CountDownLatch init(String samplerData) {
        sampleResult=new SampleResult();
        sampleResult.sampleStart();
        sampleResult.setSamplerData(samplerData);
        sampleResult.setDataType(SampleResult.TEXT);
        countDownLatch= ThreadUtil.newCountDownLatch(1);

        return countDownLatch;
    }


    public void end(String name,String code, String response){
        if (sampleResult==null){
            init(null);
        }
        sampleResult.setSampleLabel(name);
        sampleResult.setResponseCode(code);
        sampleResult.setResponseData(response, StandardCharsets.UTF_8.name());
        if ("200".equals(code)){
            sampleResult.setSuccessful(true);
        }else{
            sampleResult.setSuccessful(false);
        }
        System.out.println(nettyClient.getName()+":"+name+"调用结束");
        sampleResult.sampleEnd();
        countDownLatch.countDown();
    }

    /**
     * 向集合中添加子结果，而不更新任何父字段。
     */
    public void addRawSubResult(String name,String code,String response, boolean renameSubResults){
        SampleResult subSampleResult = new SampleResult();
        subSampleResult.setSampleLabel(name);
        subSampleResult.setResponseCode(code);
        subSampleResult.setResponseData(response, StandardCharsets.UTF_8.name());
        if ("200".equals(code)){
            subSampleResult.setSuccessful(true);
        }else{
            subSampleResult.setSuccessful(false);
        }
        if (sampleResult==null){
            init(null);
        }
        this.sampleResult.storeSubResult(subSampleResult,renameSubResults);
    }

    public SampleResult getSampleResult() {
        return sampleResult;
    }
}
